package mysql

import "gorm.io/gorm"

type Cart struct {
	gorm.Model
	UserId     int64   `gorm:"column:user_id;type:int(11);not null;index;comment:用户ID"`
	GoodsId    int64   `gorm:"column:goods_id;type:int(11);not null;comment:商品ID"`
	GoodsPrice float32 `gorm:"column:goods_price;type:decimal(10,2);not null;comment:商品价格0"`
	Quantity   int64   `gorm:"column:quantity;type:int(11);not null;comment:购买数量"`
	GoodsTitle string  `gorm:"column:goods_title;type:varchar(50);not null;comment:商品标题"`
	GoodsCover string  `gorm:"column:goods_cover;type:varchar(100);not null;comment:商品封面"`
	Checked    int64   `gorm:"column:checked;type:int(11);not null;comment:是否勾选"`
}

// CartList 购物车列表
func (c *Cart) CartList(goodsTitle string) (carts []*Cart, err error) {

	if goodsTitle != "" {
		mysqlClient = mysqlClient.Where("goods_title like ?", "%"+goodsTitle+"%")
	}

	err = mysqlClient.Find(&carts).Error
	return
}

// 查询购物车中是否存在该商品
func (c *Cart) Exist() (exist bool) {
	mysqlClient.Where("user_id = ? and goods_id = ?", c.UserId, c.UserId).First(&c)
	exist = c.ID > 0
	return
}

// 添加购物车
func (c *Cart) Add() error {
	return mysqlClient.Create(&c).Error
}

// 移除购物车
func (c *Cart) Remove() error {
	return mysqlClient.Where("user_id = ? and goods_id = ?", c.UserId, c.GoodsId).Delete(&c).Error
}

// 清空购物车
func (c *Cart) RemoveAll() error {
	return mysqlClient.Where("user_id = ?", c.UserId).Delete(&c).Error
}

// 更新购物车的商品数量
func (c *Cart) UpdateQuantity() error {
	return mysqlClient.Model(&c).Update("quantity", c.Quantity).Error
}
